package com.guoxin.thread.concurrent.chapter9;

public class ProducerConsumerVersion3 {

    private int i = 0;

    private final Object LOCK = new Object();

    private volatile boolean isProduced = false;

    public void producer() {
        synchronized (LOCK) {
            while (isProduced) {
                try {
                    LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            i++;
            System.out.println("生产数据>>" + i);
            LOCK.notifyAll();
            isProduced = true;
        }
    }

    public void consumer() {
        synchronized (LOCK) {
            while (isProduced) {
                System.out.println("消费数据>>" + i);
                LOCK.notifyAll();
                isProduced = false;
            }
            try {
                LOCK.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ProducerConsumerVersion3 pc = new ProducerConsumerVersion3();

        new Thread("P") {
            @Override
            public void run() {
                while (true) {
                    pc.producer();
                }
            }
        }.start();


        new Thread("P2") {
            @Override
            public void run() {
                while (true) {
                    pc.producer();
                }
            }
        }.start();

        new Thread("C") {
            @Override
            public void run() {
                while (true) {
                    pc.consumer();
                }
            }
        }.start();

        new Thread("C2") {
            @Override
            public void run() {
                while (true) {
                    pc.consumer();
                }
            }
        }.start();

        new Thread("C3") {
            @Override
            public void run() {
                while (true) {
                    pc.consumer();
                }
            }
        }.start();
    }
}
